package com.bootdo.common.controller;

import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.domain.FileDO;
import com.bootdo.common.service.FileService;
import com.bootdo.common.utils.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.*;

/**
 * 文件上传
 * 
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2017-09-19 16:02:20
 */
@Controller
@RequestMapping("/common/sysFile")
public class FileController extends BaseController {

	@Autowired
	private FileService sysFileService;

	@Autowired
	private BootdoConfig bootdoConfig;

	@GetMapping()
	//@RequiresPermissions("common:sysFile:sysFile")
	String sysFile(Model model) {
		Map<String, Object> params = new HashMap<>(16);
		return "common/file/file";
	}

	@ResponseBody
	@GetMapping("/list")
	//@RequiresPermissions("common:sysFile:sysFile")
	public PageUtils list(@RequestParam Map<String, Object> params) {
		// 查询列表数据
		Query query = new Query(params);
		List<FileDO> sysFileList = sysFileService.list(query);
		int total = sysFileService.count(query);
		PageUtils pageUtils = new PageUtils(sysFileList, total);
		return pageUtils;
	}

	@GetMapping("/add")
	// @RequiresPermissions("common:bComments")
	String add() {
		return "common/sysFile/add";
	}

	@GetMapping("/edit")
	// @RequiresPermissions("common:bComments")
	String edit(Long id, Model model) {
		FileDO sysFile = sysFileService.get(id);
		model.addAttribute("sysFile", sysFile);
		return "common/sysFile/edit";
	}

	/**
	 * 信息
	 */
	@RequestMapping("/info/{id}")
	//@RequiresPermissions("common:info")
	public R info(@PathVariable("id") Long id) {
		FileDO sysFile = sysFileService.get(id);
		return R.ok().put("sysFile", sysFile);
	}

	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	//@RequiresPermissions("common:save")
	public R save(FileDO sysFile) {
		if (sysFileService.save(sysFile) > 0) {
			return R.ok();
		}
		return R.error();
	}

	/**
	 * 修改
	 */
	@RequestMapping("/update")
	//@RequiresPermissions("common:update")
	public R update(@RequestBody FileDO sysFile) {
		sysFileService.update(sysFile);

		return R.ok();
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ResponseBody
	// @RequiresPermissions("common:remove")
	public R remove(Long id, HttpServletRequest request) {
		if ("test".equals(getUsername())) {
			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
		}
		String fileName = bootdoConfig.getUploadPath() + sysFileService.get(id).getFileOwner()+"/"+sysFileService.get(id).getFileName();
		if (sysFileService.remove(id) > 0) {
			boolean b = FileUtil.deleteFile(fileName);
			if (!b) {
				return R.error("数据库记录删除成功，文件删除失败");
			}
			return R.ok();
		} else {
			return R.error();
		}
	}

	/**
	 * 删除
	 */
	@PostMapping("/batchRemove")
	@ResponseBody
	//@RequiresPermissions("common:remove")
	public R remove(@RequestParam("ids[]") Long[] ids) {
		if ("test".equals(getUsername())) {
			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
		}
		sysFileService.batchRemove(ids);
		return R.ok();
	}

	//删除指定用户下所有文件
	@PostMapping("/batchRemoveByFileOwner")
	@ResponseBody
	public R batchRemoveByFileOwner(@RequestParam("fileOwner")String fileOwner){
		sysFileService.batchRemoveByFileOwner(fileOwner);
		return R.ok();
	}

	//删除指定用户下文件
	@PostMapping("/removeFile")
	@ResponseBody
	public R removeFile(@RequestParam Map<String, Object> params){
		String fileName = (String) params.get("fileName");
		if(fileName == null || fileName == ""){
			return R.error(-102,"文件名参数为空");
		}
		String fileOwner = (String) params.get("fileOwner");
		if(fileOwner == null || fileOwner == ""){
			return R.error(-102,"文件所属用户参数为空");
		}

		String filePath = bootdoConfig.getUploadPath() + fileOwner+"/"+fileName;

		if (sysFileService.removeFile(params) > 0) {
			boolean b = FileUtil.deleteFile(filePath);
			if (!b) {
				return R.error("数据库记录删除成功，文件删除失败");
			}
			return R.ok();
		} else {
			return R.error();
		}
	}

	@ResponseBody
	@PostMapping("/upload")
	public R upload(@RequestParam("file") MultipartFile file,@RequestParam(value = "fileOwner",required = false) String fileOwner) {
//		if ("test".equals(getUsername())) {
//			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
//		}
		String fileName = file.getOriginalFilename();
		//fileName = FileUtil.renameToUUID(fileName);

		String userName = "";
		try {
			userName = getUsername();
		} catch (Exception e){
			userName = "";
		}

		if((userName == null || userName == "") && fileOwner != null && fileOwner != "" ){
			userName = fileOwner;
		} else if((userName == null || userName == "") && (fileOwner == null || fileOwner == "" )){
			return R.error(-102,"文件所属用户参数为空");
		}


		//判定文件是否存在
		if(sysFileService.isExist(fileName,userName)){
			return R.error(-101,"文件已存在");
		}
		FileDO sysFile = new FileDO(FileType.fileType(fileName), fileName, userName, new Date());
		try {
			FileUtil.uploadFile(file.getBytes(), bootdoConfig.getUploadPath()+sysFile.getFileOwner()+"/", fileName);
		} catch (Exception e) {
			return R.error();
		}

		if (sysFileService.save(sysFile) > 0) {
			return R.ok().put("fileName",bootdoConfig.getUploadPath()+sysFile.getFileOwner()+"/"+sysFile.getFileName());
		}
		return R.error();
	}


	//获取指定用户下的文件列表
	@ResponseBody
	@GetMapping("/getFileListByFileOwner")
	public R getFileListByFileOwner(@RequestParam("fileOwner")String fileOwner){
		List<FileDO> sysFileList = sysFileService.getByFileOwner(fileOwner);
		if(sysFileList.size()>0){
			List<String> fileUrls = new ArrayList<String>();
			for(FileDO file : sysFileList){
				String fileName = file.getFileName();
				fileUrls.add(bootdoConfig.getUploadPath()+fileOwner+"/"+fileName);
			}
			return R.ok().put("fileOwner",fileOwner).put("fileUrls",fileUrls);
		}else if(sysFileList.size() == 0){
			return R.ok().put("fileOwner",fileOwner).put("fileUrls",new ArrayList<String>());
		}
		return R.error();
	}

	//根据文件名+用户名获取指定文件路径
	@ResponseBody
	@GetMapping("/getFilePath")
	public R getFilePath(@RequestParam Map<String, Object> params){
		String fileName = (String) params.get("fileName");
		if(fileName == null || fileName == ""){
			return R.error(-102,"文件名参数为空");
		}
		String fileOwner = (String) params.get("fileOwner");
		if(fileOwner == null || fileOwner == ""){
			return R.error(-102,"文件所属用户参数为空");
		}
		FileDO sysFile = sysFileService.getFile(params);
		if(sysFile != null){
			return R.ok().put("fileOwner",fileOwner).put("fileUrl",bootdoConfig.getUploadPath()+fileOwner+"/"+fileName);
		}
		return R.error();
	}

	//根据文件名+用户名下载指定文件
	@ResponseBody
	@GetMapping("/downloadFile")
	public void downloadFile(HttpServletResponse response, @RequestParam("fileName")String fileName, @RequestParam("fileOwner")String fileOwner){
		String path = bootdoConfig.getUploadPath()+fileOwner+"/"+fileName;

		String outFileName = null;
		try {
			outFileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		File file = new File(path);
		response.reset();
		response.setContentType("application/octet-stream");
		response.setCharacterEncoding("utf-8");
		response.setContentLength((int) file.length());
		response.setHeader("Content-Disposition", "attachment;filename=" + outFileName);
		byte[] buff = new byte[1024];
		BufferedInputStream bis = null;
		OutputStream os = null;
		try {
			os = response.getOutputStream();
			bis = new BufferedInputStream(new FileInputStream(file));
			int i = 0;
			while ((i = bis.read(buff)) != -1) {
				os.write(buff, 0, i);
				os.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


}
